package com.hsnn.medstgmini.pro.base.service.Impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.hsnn.medstgmini.Constants;
import com.hsnn.medstgmini.base.dict.model.form.DicAreaForm;
import com.hsnn.medstgmini.base.dict.service.DicAreaManager;
import com.hsnn.medstgmini.pro.base.dao.BaseDelrelationDao;
import com.hsnn.medstgmini.pro.base.dao.BaseGoodsDao;
import com.hsnn.medstgmini.pro.base.model.BaseDelrelation;
import com.hsnn.medstgmini.pro.base.model.BaseDelrelationLog;
import com.hsnn.medstgmini.pro.base.model.BaseGoods;
import com.hsnn.medstgmini.pro.base.model.DelStatus;
import com.hsnn.medstgmini.pro.base.model.form.BaseDelrelationForm;
import com.hsnn.medstgmini.pro.base.model.form.DrugByPSForm;
import com.hsnn.medstgmini.pro.base.service.BaseDelrelationManager;
import com.hsnn.medstgmini.util.ConstantsUtil;
import com.hsnn.medstgmini.util.Pagination;
import com.hsnn.medstgmini.util.ParseDate;
import com.hsnn.medstgmini.util.ParseNumber;
@Service("baseDelrelationManager")
public class BaseDelrelationManagerImpl implements BaseDelrelationManager {
	@Autowired
	private BaseDelrelationDao baseDelrelationDao;
	@Transactional
	public void confirmDel(Pagination page){
		baseDelrelationDao.confirmDel(page);
	}
	@Autowired
	private BaseGoodsDao baseGoodsDao;
	@Value("#{sysProp['system.setpuDelNumConfig']}")
	private String setpuDelNumConfig;
	@Autowired
	private DicAreaManager dicAreaManger;
	@Value("#{sysProp['system.linxuan']}")
	private boolean linxuan;
	
	/**
	 * @category 根据id查询配送企业详情
	 * @author 张俊
	 * @date 2015-06-18
	 * @param id
	 * @return
	 */
	public BaseDelrelation getBaseDelrelationById(String id) {
		return baseDelrelationDao.getBaseDelrelationById(id);
	}
	
	/**
	 * @category 解除配送关系
	 * @author 张俊
	 * @date 2015-06-18
	 * @param baseDelrelation
	 * @return
	 */
	public void changeStatus(BaseDelrelation baseDelrelation) {
		baseDelrelationDao.changeStatus(baseDelrelation);
	}
	/**
	 * 
	 *@category 查询当前生产企业的所有药品配送关系
	 *@author 单大伟
	 *@date 2015年6月18日
	 *@param page
	 *@return
	 */
	@SuppressWarnings("unchecked")
	public Pagination getBaseDelRelationList(Pagination page) {
		page = baseDelrelationDao.getBaseDelRelationList(page);
		page.setRows(formateDel((List<Object[]>) page.getRows()));
		return page;
	}
	private List<BaseGoods> formateDel(List<Object[]> list){
		List<BaseGoods> flist = new ArrayList<BaseGoods>();
		if (null != list && list.size() > 0){
			for (int i = 0; i < list.size(); i++){
				Object[] obj = list.get(i);
				BaseGoods data = new BaseGoods();
				data.setDelRelId(obj[0]==null?"":obj[0].toString());
				data.setGoodsCode(obj[1]==null?"":obj[1].toString());
				data.setDrugCode(obj[2]==null?"":obj[2].toString());
				data.setDrugName(obj[3]==null?"":obj[3].toString());
				data.setFormName(obj[4]==null?"":obj[4].toString());
				data.setSpecName(obj[5]==null?"":obj[5].toString());
				data.setFactor(obj[6]==null?"":obj[6].toString());
				data.setUnit(obj[7]==null?"":obj[7].toString());
				data.setMaterialName(obj[8]==null?"":obj[8].toString());
				data.setCompName(obj[9]==null?"":obj[9].toString());
				data.setAreaName(obj[10]==null?"":obj[10].toString());
				data.setProPriceLimit(Double.parseDouble(obj[11]==null?"":obj[11].toString()));
				data.setDrugId(obj[12]==null?"":obj[12].toString());
				data.setProdPompId(obj[13]==null?"":obj[13].toString());
				data.setStatusText(obj[14]==null?"":(obj[14].toString().equals("0")?"未确认":(obj[14].toString().equals("1")?"已确认":(obj[14].toString().equals("2")?"拒绝":"解除"))));
				data.setRetailPriceLimit(Double.parseDouble(obj[15]==null?"":obj[15].toString()));
				flist.add(data);
			}
		}
		return flist;
	}
	
	public List<BaseDelrelationLog> getBaseDelRelationLogList(Pagination page, BaseDelrelationLog baseDelrelationLog) {
		return baseDelrelationDao.getBaseDelRelationLogList(page, baseDelrelationLog);
	}
	
	@SuppressWarnings("unchecked")
	public Pagination getBaseDelRelationLogByPs(Pagination page){
		page = baseDelrelationDao.getBaseDelRelationLogByPs(page);
		page.setRows(formatLogByPs((List<Object[]>) page.getRows()));
		return page;
	}
	private List<DrugByPSForm> formatLogByPs(List<Object[]> list){
		List<DrugByPSForm> flist = new ArrayList<DrugByPSForm>();
		if (null != list && list.size() > 0){
			for (int i = 0; i < list.size(); i ++){
				DrugByPSForm form = new DrugByPSForm();
				Object[] obj = list.get(i);
				form.setGoodsCode(obj[0]==null?"":obj[0].toString());
				form.setDrugCode(obj[1]==null?"":obj[1].toString());
				form.setDrugName(obj[2]==null?"":obj[2].toString());
				form.setFormName(obj[3]==null?"":obj[3].toString());
				form.setSpecName(obj[4]==null?"":obj[4].toString());
				form.setFactor(obj[5]==null?"":obj[5].toString());
				form.setUnit(obj[6]==null?"":obj[6].toString());
				form.setMaterialName(obj[7]==null?"":obj[7].toString());
				form.setCompName(obj[8]==null?"":obj[8].toString());
				form.setAreaName(obj[9]==null?"":obj[9].toString());
				form.setProPriceLimit(obj[10]==null?"":ParseNumber.toStrDecimal(ParseNumber.toDouble(obj[10].toString())));
				form.setStatus(obj[11]==null?"":DelStatus.getName(Integer.parseInt(obj[11].toString())));
				form.setUpdDatetime(obj[12]==null?"":obj[12].toString().substring(0, 19));
				form.setUpdUser(obj[13]==null?"":obj[13].toString());
				form.setDrugId(obj[14]==null?"":obj[14].toString());
				form.setProdCompId(obj[15]==null?"":obj[15].toString());
				flist.add(form);
			}
		}
		return flist;
	}

	@SuppressWarnings("unchecked")
	@Override
	public Pagination getDrugByPS(Pagination page) {
		page = baseDelrelationDao.getDrugByPS(page);
		List<Object[]> list = (List<Object[]>) page.getRows();
		List<DrugByPSForm> flist = new ArrayList<DrugByPSForm>();
		if (null != list && list.size() > 0){
			for (int i = 0; i < list.size(); i++) {
				Object[] obj = list.get(i);
				DrugByPSForm form = new DrugByPSForm();
				form.setGoodsCode(obj[0]==null?"":obj[0].toString());
				form.setDrugCode(obj[1]==null?"":obj[1].toString());
				form.setDrugName(obj[2]==null?"":obj[2].toString());
				form.setFormName(obj[3]==null?"":obj[3].toString());
				form.setSpecName(obj[4]==null?"":obj[4].toString());
				form.setFactor(obj[5]==null?"":obj[5].toString());
				form.setUnit(obj[6]==null?"":obj[6].toString());
				form.setMaterialName(obj[7]==null?"":obj[7].toString());
				form.setCompName(obj[8]==null?"":obj[8].toString());
				form.setCount(obj[9]==null?"":obj[9].toString());
				form.setProPriceLimit(obj[10]==null?"":ParseNumber.toStrDecimal(ParseNumber.toDouble(obj[10].toString())));
				form.setDrugId(obj[11]==null?"":obj[11].toString());
				form.setProdCompId(obj[12]==null?"":obj[12].toString());
				flist.add(form);
			}
		}
		page.setRows(flist);
		return page;
	}
	
	/**
	 * 
	 * @category 配送企业配送的药品的所有配送区域
	 * @author 张俊
	 * @date 2015-06-25 17:12:44
	 * @param 
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public Pagination getDrugByPSArea(Pagination page) {
		page = baseDelrelationDao.getDrugByPSArea(page);
		List<DicAreaForm> flist = new ArrayList<DicAreaForm>();
		List<Object[]> list = (List<Object[]>) page.getRows();
		if (list != null && list.size() > 0) {
			for (int i = 0; i < list.size(); i++) {
				Object[] obj = (Object[]) list.get(i);
				DicAreaForm form = new DicAreaForm();
				form.setDelRelId(obj[0]==null?"":obj[0].toString());
				form.setAreaId(obj[1]==null?"":obj[1].toString());
				form.setAreaName(obj[2]==null?"":obj[2].toString());
				form.setFatherAreaCode(obj[3]==null?"":obj[3].toString());
				form.setFatherAreaName(obj[4]==null?"":obj[4].toString());
				flist.add(form);
			}
		}
		page.setRows(flist);
		return page;
	}
	/**
	 * 
	 *@category 获取中心设置商品配送关系列表
	 *@author 邱磊
	 *@date 2015年6月17日 上午11:06:06
	 *@param page
	 *@return
	 */
	public Pagination getDelDrugDataList(Pagination page){
		page = baseDelrelationDao.getDelDrugDataList(page);
		return page;
	}
	
	public Pagination getCenterDelByAreaList(Pagination page){
		return null;
	}
	
	
	
	@Transactional
	public void removeDell(List<String> list,String updUser){
		baseDelrelationDao.removeDell(list,updUser);
	}
	/**
	 * 
	 *@category 获取未被遴选的配送企业
	 *@author 邱磊
	 *@date 2015年11月19日 下午8:28:38
	 *@param 
	 *@return Pagination
	 */
	@SuppressWarnings("unchecked")
	public Pagination getSelectDelData(Pagination page){
		page = baseDelrelationDao.getSelectDelData(page);
		List<Map<String, Object>> list = (List<Map<String, Object>>) page.getRows();
		page.setRows(list);
		return page;
	}
	@SuppressWarnings("unchecked")
	public Pagination getSelectDelResultData(Pagination page){
		page = baseDelrelationDao.getSelectDelData(page);
		List<Map<String, Object>> list = (List<Map<String, Object>>) page.getRows();
		if (null != list && list.size() > 0){
			for (int i = 0; i < list.size(); i++){
				Map<String, Object> map = list.get(i);
				if (null == map.get("del_range") || "".equals(map.get("del_range").toString())){
					map.put("del_range", "");
				} else {
					if (!"1".equals(map.get("status").toString())){
						if ("0".equals(map.get("del_range").toString())){
							map.put("del_range", ConstantsUtil.delRange(String.valueOf(Constants.DEL_RANGE_BASE)) + "，" + ConstantsUtil.delRange(String.valueOf(Constants.DEL_RANGE_COUNTY)));
						} else {
							map.put("del_range", ConstantsUtil.delRange(map.get("del_range").toString()));
						}
					} else {
						map.put("del_range", "");
					}
				}
			}
		}
		page.setRows(list);
		return page;
	}
	@SuppressWarnings("unchecked")
	public Pagination confirmDelArea(Pagination page){
		String areaCode = page.getConditions().get("areaCode");
		//根据地区编码获取地区信息
		Map<String, Object> map = dicAreaManger.getAreaByAreaId(areaCode);
		//地区最大基层配送限制数
		int maxBaseNum = map.get("max_delnum_base") == null ? 0 : "".equals(map.get("max_delnum_base").toString()) ? 0 : ParseNumber.toInteger(map.get("max_delnum_base").toString());
		//地区最大县级以上配送限制数
		int maxCountyNum = map.get("max_delnum_county") == null ? 0 : "".equals(map.get("max_delnum_county").toString()) ? 0 : ParseNumber.toInteger(map.get("max_delnum_county").toString());
		List<BaseDelrelationForm> list = (List<BaseDelrelationForm>) page.getRows();
		page.setRows(null);
		int thisBaseNum = 0;//本次要设的基层数
		int thisCountyNum = 0;//本次要设的县级以上数
		List<String> paramList = new ArrayList<String>();
		if (null != list && list.size() > 0){
			for (int i = 0; i < list.size(); i++){//取出本次要设置的数据
				BaseDelrelationForm form = list.get(i);
				paramList.add(form.getDelRelId());
				form.setStatus(String.valueOf(Constants.DEL_SELECT_STATUS_WEILINXUAN));//初始化配送企业的设置状态为”未遴选“
				if (form.getBaseDelRange()){//配送企业在该地区的基层配送已勾选
					thisBaseNum ++;//本次设的基层数加1
					form.setRange(Constants.DEL_RANGE_BASE);//将本条配送企业的配送范围设为”基层“
					form.setStatus(String.valueOf(Constants.DEL_SELECT_STATUS_LINXUANTONGUO));//将配送企业状态改为”遴选通过“
				}
				if (form.getCountyDelRange()){//配送企业在该地区的县级以上配送已勾选
					thisCountyNum ++;//本次设的县级以上数加1
					if (null != form.getRange() && Constants.DEL_RANGE_BASE == form.getRange()){//该地区配送企业已经勾选了基层（即表示全选了）
						form.setRange(Constants.DEL_RANGE_ALL);//配送范围设为全选
					} else {
						form.setRange(Constants.DEL_RANGE_COUNTY);//配送范围设为县级以上
						form.setStatus(String.valueOf(Constants.DEL_SELECT_STATUS_LINXUANTONGUO));//将配送企业状态改为”遴选通过“
					}
				}
				if (!form.getBaseDelRange() && !form.getCountyDelRange()){//如果两个都没有勾选，将状态设置为未遴选
					form.setStatus(String.valueOf(Constants.DEL_SELECT_STATUS_WEILINXUAN));
				}
			}
			//根据地区编码，基层配送范围获取已该地区已设置的基层配送企业数（排除本次勾选的数据）
			Map<String, Object> baseDel = baseDelrelationDao.getHaveDelNum(areaCode, Constants.DEL_RANGE_BASE,paramList);
			int haveBaseNum = ParseNumber.toInteger(baseDel.get("delCount").toString());
			//根据地区编码，县级以上配送范围获取已该地区已设置的县级以上配送企业数（排除本次勾选的数据）
			Map<String, Object> countyDel = baseDelrelationDao.getHaveDelNum(areaCode, Constants.DEL_RANGE_COUNTY,paramList);
			int haveCountyNum = ParseNumber.toInteger(countyDel.get("delCount").toString());
			if (0 != maxBaseNum){//该地区已设置了基层配送大最数限制
				if (maxBaseNum < (thisBaseNum + haveBaseNum)){//本次勾选的基层配送数+系统中已设过的基层数超过了最大数限制
					page.setSuccess(false);
					page.setMsg("您勾选的基层配送已超过最大最限制，该地区最多还可以设置" + (maxBaseNum - haveBaseNum) + "家基层配送企业！");
					return page;
				}
			}
			if (0 != maxCountyNum){//该地区已设置了县及县以上配送大最数限制
				if (maxCountyNum < (thisCountyNum + haveCountyNum)){//本次勾选的县级县以上配送数+系统中已设过的县及县以上数超过了最大数限制
					page.setSuccess(false);
					page.setMsg("您勾选的县及县以上配送已超过最大最限制，该地区最多还可以设置" + (maxCountyNum - haveCountyNum) + "家县及县以上配送企业！");
					return page;
				}
			}
			baseDelrelationDao.confirmDelArea(list);
			page.setSuccess(true);
			page.setMsg("遴选成功！");
			return page;
		}
		page.setSuccess(false);
		page.setMsg("请刷新页面后重新设置！");
		return page;
	}


	@Override
	public Pagination batchDeclare(Pagination page) {
		return baseDelrelationDao.batchDeclare(page);
	}

	@SuppressWarnings("unchecked")
	@Override
	public Pagination getDelRangeResultByPs(Pagination page) {
		page =  baseDelrelationDao.getDelRangeResultByPs(page);
		List<Map<String, Object>> list = (List<Map<String, Object>>) page.getRows();
		if (null != list && list.size() > 0){
			for (int i = 0; i < list.size(); i++){
				Map<String, Object> map = list.get(i);
				Object delRange = map.get("delRange");
				if (null == delRange || "".equals(delRange.toString())){
					map.put("delRange", "");
				} else {
					if (!"1".equals(map.get("status").toString())){
						if ("0".equals(delRange.toString())){
							map.put("delRange", ConstantsUtil.delRange(String.valueOf(Constants.DEL_RANGE_BASE)) + "，" + ConstantsUtil.delRange(String.valueOf(Constants.DEL_RANGE_COUNTY)));
						} else {
							map.put("delRange", ConstantsUtil.delRange(delRange.toString()));
						}
					} else {
						map.put("delRange", "");
					}
				}
			}
		}
		return page;
	}
	public Pagination getDelByHospData(Pagination page){
		return baseDelrelationDao.getDelByHospData(page);
	}
	
	public Pagination getSetDelByHospWithDelcompData(Pagination page){
		if (linxuan){
			return baseDelrelationDao.getSetDelByHospWithLXDelcompData(page);
		}
		return baseDelrelationDao.getSetDelByHospWithDelcompData(page);
	}
	public Pagination setDelByHospWithDelcomp(Pagination page){
		baseDelrelationDao.setDelByHospWithDelcomp(page);
		page.setSuccess(true);
		page.setMsg("设置成功！");
		return page;
	}
	@SuppressWarnings("unchecked")
	public Pagination getDelByHospLogData(Pagination page){
		page = baseDelrelationDao.getDelByHospData(page);
		List<Map<String, Object>> list = (List<Map<String, Object>>) page.getRows();
		if (null != list && list.size() > 0){
			for (int i = 0; i < list.size(); i++){
				Map<String, Object> map = list.get(i);
				map.put("status", map.get("status")==null?"":ConstantsUtil.delStatus(map.get("status").toString()));
				map.put("upd_datetime", map.get("upd_datetime")==null?"":ParseDate.parseFullFormat(ParseDate.fromFullFormat(map.get("upd_datetime").toString())));
			}
		}
		return page;
	}
	public Pagination getDelProdCompData(Pagination page){
		return baseDelrelationDao.getDelProdCompData(page);
	}
	
	public Pagination getBaseDelCentreWithHospList(Pagination page){
		page = baseDelrelationDao.getBaseDelCentreWithHospList(page);
		return page;
	}
	
	/**
	 * @category 配送企业获取待确认配送的商品数据
	 * @author 韩守松
	 * @date   2015年12月8日
	 * @param  @return
	 */
	public Pagination getWaitDelOKGoods(Pagination page){
		return baseDelrelationDao.getWaitDelOKGoods(page);
	}
}
